import {createRouter, createWebHashHistory} from "vue-router"
import Router from "./router";
import NProgress from 'nprogress'; // Progress 进度条;
import 'nprogress/nprogress.css'; // Progress 进度条样式
import Config from "@/settings";
import {getToken, getUserInfo} from '@/utils/auth';
import store from "../store";
import {error} from "../utils/message";

const router = createRouter({
    history: createWebHashHistory(),
    routes: Router
});
NProgress.configure({ease: 'linear', speed: 500})
const whiteList = ['/login']// no redirect whitelist
router.beforeEach(((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title + ' - ' + Config.title
    }
    NProgress.start();
    if (getToken()) {
        // 已登录且要跳转的页面是登录页
        if (to.path === '/login') {
            next({path: '/'})
            NProgress.done()
        } else {
            let data = router.getRoutes().length;

            if (data <= 3) {
                let userInfo = getUserInfo();
                store.dispatch("permissionOperation", userInfo).then(() => {
                    next(to);
                }).catch(err => error(err));
                return;
            }
            let toPath = router.getRoutes().find(item => item.path === to.path)
            if (toPath) {
                next()
            } else {
                next({path: '/'})
            }

        }
    } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next()
        } else {
            next({path: `/login?redirect=${to.fullPath}`}) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
}));
router.beforeResolve(((to, from, next) => {
    // console.log(to);
    // console.log(from);
    next();
}));
router.afterEach(((to, from) => {
    if (to.path !== "/login") {
        let componentName = to.matched[to.matched.length - 1].components["default"].name;
        let path = to.path;
        let name = to.meta.title;
        store.dispatch("commitNavBar", {name, path, componentName})
    }
    NProgress.done();
}))
export default router;